﻿using Common.Communal;
using MediatR;
using Product.API.Read.Applications.Commands.Material;
using SqlSugar;

namespace Product.API.Read.Applications.CommandHandlers.Material
{
    /// <summary>
    /// 物料显示命令处理
    /// </summary>
    public class MaterialShowCommandHandler : IRequestHandler<MaterialShowCommand, ApiResult<ApiPaging<ERP.Domain.Products.Material>>>
    {
        /// <summary>
        /// SqlSugar
        /// </summary>
        private readonly ISqlSugarClient db;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="db">SqlSugar</param>
        public MaterialShowCommandHandler(ISqlSugarClient db)
        {
            this.db = db;
        }

        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回任务</returns>
        public Task<ApiResult<ApiPaging<ERP.Domain.Products.Material>>> Handle(MaterialShowCommand request, CancellationToken cancellationToken)
        {
            ApiResult<ApiPaging<ERP.Domain.Products.Material>> result = new ApiResult<ApiPaging<ERP.Domain.Products.Material>>();
            result.Code = EnumCode.Ok;
            result.Message = EnumCode.Ok.ToString();

            int totalCount = 0;
            int totalPage = 0;
            var data = db.Queryable<ERP.Domain.Products.Material>().Where(x => x.IsDelete == false).ToPageList(request.pageIndex, request.pageSize, ref totalCount, ref totalPage);

            // 物料名称
            if (request.MaterialName != null)
            {
                data = data.Where(x => x.MaterialName.Contains(request.MaterialName)).ToList();
            }

            // 物料类型
            if (request.MaterialType != null)
            {
                data = data.Where(x => x.MaterialType.Equals(request.MaterialType)).ToList();
            }

            // 启用状态
            if (request.ActivationStatus != null)
            {
                data = data.Where(x => x.ActivationStatus.Equals(request.ActivationStatus)).ToList();
            }

            // 物料分类
            if (request.MaterialClassification != null)
            {
                data = data.Where(x => x.MaterialClassification.Equals(request.MaterialClassification)).ToList();
            }

            // 物料属性
            if (request.MaterialAttribute != null)
            {
                data = data.Where(x => x.MaterialAttribute.Equals(request.MaterialAttribute)).ToList();
            }

            ApiPaging<ERP.Domain.Products.Material> page = new ApiPaging<ERP.Domain.Products.Material>();
            page.TotalCount = totalCount;
            page.TotalPage = totalPage;
            page.Data = data;
            result.Data = page;

            return Task.FromResult(result);
        }
    }
}
